import requests
import datetime


def get_csrf_cookie(url):
    login_url = f'{url}/c/login'
    response = requests.get(login_url)    
    headers = {}
    cookies = {}
    headers['X-Harbor-Csrf-Token'] = response.headers.get('X-Harbor-Csrf-Token')
    cookies['_gorilla_csrf'] = response.cookies.get('_gorilla_csrf')
    cookies['sid'] = response.cookies.get('sid')

    return headers, cookies


def login(url, data, headers, cookies):
    login_url = f'{url}/c/login'
    response = requests.post(login_url, data=data, headers=headers, cookies=cookies)
    headers = {}
    cookies = {}
    headers['X-Harbor-Csrf-Token'] = response.headers.get('X-Harbor-Csrf-Token')
    cookies['sid'] = response.cookies.get('sid')
    
    return headers, cookies

def get_harbor_log(url, headers, cookies):
    yesterday = (datetime.date.today() - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
    for i in range(1, 1000):
        log_url = f'{url}?page_size=100&page={i}'
        response = requests.get(log_url, headers=headers, cookies=cookies)
                
        # with open(f'page{i}', 'w', encoding='utf-8') as f:
        #     f.write(response.text)

        if response.json()[-1].get('op_time') < yesterday:
            break   


if __name__ == '__main__':
    harbor_url = ''
    log_url = f'{harbor_url}/api/v2.0/audit-logs'
    login_data = {
        "principal": "",
        "password": ""
    }  
 
    headers, cookies = get_csrf_cookie(harbor_url)
    headers, cookies = login(harbor_url, login_data, headers, cookies)
    try:
        get_harbor_log(log_url, headers, cookies)
        print("获取harbor日志完成。")
    except Exception as e:
        print("获取harbor日志出错：", e)
